<?php
include_once('./simple_html_dom.php');

// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("otafood") or die(mysql_error());

// Making the xml object
$xml = new  SimpleXMLElement('<friends></friends>');

// Get the http GET parameters
$id = $_GET["id"];
$name = $_GET["name"];
$friends = $_GET["friends"];

$key = 'You can never guess me';

$td = mcrypt_module_open ('des', '', 'ecb', ''); 
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND); 
mcrypt_generic_init ($td, $key, $iv); 
$decodedId = base64_decode($id);
$id_decrypt = mdecrypt_generic ($td, $decodedId); 

mcrypt_generic_init ($td, $key, $iv); 
$decodedName = base64_decode($name);
$name_decrypt = mdecrypt_generic ($td, $decodedName); 

$trimmed = preg_replace('/[^(\x20-\x7F)]*/','', $id_decrypt);
$response = file_get_contents("http://graph.facebook.com/". $trimmed . "?fields=name");
$arr = json_decode($response);
$name_facebook = preg_replace('/[^(\x20-\x7F)]*/','', $arr->{"name"});

// Check if the facebook id is valid
if($name_facebook === preg_replace('/[^(\x20-\x7F)]*/','', $name_decrypt)){

	$friends_array = explode('+', $friends);
	foreach($friends_array as $key => $value) {
		$result = mysql_query('SELECT * from book WHERE id_facebook=' . preg_replace('/[^(\x20-\x7F)]*/','', $value) . ' AND time >= now()');
		if(!$result)
			echo "error in the query";
		else{
			while ($row = mysql_fetch_assoc($result)) {
				$friend_xml = $xml->addChild('friend');
				$friend_xml->addChild('id', $row["id"]);
				$friend_xml->addChild('restaurant', $row["restaurant"]);
				$friend_xml->addChild('time', $row["time"]);
			}
		}
	}

}
else
	echo "Invalid facebook id."	;


header ("Content-Type:text/xml"); 
echo $xml->asXML();


?>
